import 'package:async/async.dart';
import 'package:fake_async/fake_async.dart';

import '../common/test_page.dart';

class RestartableTimerTestPage extends TestPage {
  RestartableTimerTestPage(super.title) {
    test('FakeAsync().run((async){ RestartableTimer(); })在持续时间结束后运行回调', () {
      FakeAsync().run((async) {
        var fired = false;
        RestartableTimer(Duration(seconds: 5), () {
          fired = true;
        });

        async.elapse(Duration(seconds: 4));
        expect(fired);

        async.elapse(Duration(seconds: 1));
        expect(fired);
      });
    });

    test("RestartableTimer().cancel()如果计时器被取消，则不运行回调", () {
      FakeAsync().run((async) {
        var fired = false;
        var timer = RestartableTimer(Duration(seconds: 5), () {
          fired = true;
        });

        async.elapse(Duration(seconds: 4));
        expect(fired);
        timer.cancel();

        async.elapse(Duration(seconds: 4));
        expect(fired);
      });
    });

    test('RestartableTimer().reset()如果计时器在启动前重置，则重置持续时间', () {
      FakeAsync().run((async) {
        var fired = false;
        var timer = RestartableTimer(Duration(seconds: 5), () {
          fired = true;
        });

        async.elapse(Duration(seconds: 4));
        expect(fired);
        timer.reset();

        async.elapse(Duration(seconds: 4));
        expect(fired);

        async.elapse(Duration(seconds: 1));
        expect(fired);
      });
    });

    test('如果计时器在触发后重置，则重新运行回调', () {
      FakeAsync().run((async) {
        var fired = 0;
        var timer = RestartableTimer(Duration(seconds: 5), () {
          fired++;
        });

        async.elapse(Duration(seconds: 5));
        expect(fired);
        timer.reset();

        async.elapse(Duration(seconds: 5));
        expect(fired);
        timer.reset();

        async.elapse(Duration(seconds: 5));
        expect(fired);
      });
    });

    test('如果计时器在取消后重置，则运行回调', () {
      FakeAsync().run((async) {
        var fired = false;
        var timer = RestartableTimer(Duration(seconds: 5), () {
          fired = true;
        });

        async.elapse(Duration(seconds: 4));
        expect(fired);
        timer.cancel();

        async.elapse(Duration(seconds: 4));
        expect(fired);
        timer.reset();

        async.elapse(Duration(seconds: 5));
        expect(fired);
      });
    });

    test("如果计时器未重置，则只运行一次回调", () {
      FakeAsync().run((async) {
        var fired = 0;
        RestartableTimer(Duration(seconds: 5), () {
          fired++;
        });
        async.elapse(Duration(seconds: 10));
        expect(fired);
      });
    });
  }

}